package com.bruceeckel.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class SerializeHelper {
    
	private static ObjectOutputStream oos =null;
	private static ObjectInputStream ois=null;
	
	/**
	 * 序列化
	 * @param object
	 * @param fileoutput
	 */
	public static void serializeObject(Object object,String fileoutput){
		    try {
				oos = new ObjectOutputStream(new FileOutputStream(fileoutput));
				oos.writeObject(object);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				closeResource();
			}
		    
//		    System.out.println("序列化：serializeObject 结束");
		   
	}
	
	/**
	 * 反序列化
	 * @param filepath
	 * @return
	 */
	public static Object deserializeObject(String filepath) {
		Object object =null;
		try {
			ois = new ObjectInputStream(new FileInputStream(filepath));
			object = ois.readObject();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			closeResource();
		}
//		System.out.println("反序列化：deserializeObject 结束");
		return object;
	}
	
	/**
	 * 序列化
	 * @param objects
	 * @param fileoutput
	 */
	public static void serializeArrayList(ArrayList<Object> objects,String fileoutput){
		ObjectOutputStream oos =null;
		    try {
				oos = new ObjectOutputStream( new FileOutputStream(fileoutput));
				oos.writeObject(objects);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				closeResource();
			}
		    
//		    System.out.println("序列化：serializeObject 结束");
	}
	
	/**
	 * 反序列化
	 * @param filepath
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static ArrayList<Object> deserializeArrayList(String filepath) {
		ArrayList<Object> objects  =null;
			try {
				ois = new ObjectInputStream(new FileInputStream(filepath));
				objects = (ArrayList<Object>) ois.readObject();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}finally{
				closeResource();
			}
			
//			System.out.println("反序列化：deserializeArrayList 结束");
		return objects;
	}
	
	/**
	 * 关闭资源
	 */
	private static void closeResource(){
		try {
			if(null!=oos){
				oos.close();
			}
			if(null!=ois){
				ois.close();
			}
		} catch (IOException e) {
		    e.printStackTrace();
//			System.out.println("SerializeHelper 资源关闭失败！");
		}
		
	}
	
}
